package com.infoland.afanmall.model.pinTuan.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RadioButton;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ToastUtils;
import com.infoland.afanmall.R;
import com.infoland.afanmall.base.util.CONST;
import com.infoland.afanmall.base.util.CacheKit;
import com.infoland.afanmall.base.util.LogKit;
import com.infoland.afanmall.base.util.ToolsKit;
import com.infoland.afanmall.base.util.okhttp.OkHttpKit;
import com.infoland.afanmall.model.pinTuan.activity.PinTuanInfoActivity;
import com.infoland.afanmall.model.pinTuan.adapter.PinTAdapter;
import com.infoland.afanmall.model.pinTuan.entity.PinTEntity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * @author 王永吉
 * @date 2018/7/13 9:52
 * 拼团主界面下方Fragment
 */
public class PinTFragment extends Fragment {

    Unbinder unbinder;
    @BindView(R.id.ptuan_rad_zui_xin)
    RadioButton ptuanRadZuiXin;
    @BindView(R.id.ptuan_rad_cheng_tuan)
    RadioButton ptuanRadChengTuan;
    @BindView(R.id.ptuan_rad_yi_pin)
    RadioButton ptuanRadYiPin;
    @BindView(R.id.you_xuan_tab)
    LinearLayout youXuanTab;
    @BindView(R.id.zhong_chou_recycle)
    RecyclerView zhongChouRecycle;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    PinTAdapter pinTAdapter;
    int activityId = 0;

    @BindView(R.id.avi_pt)
    AVLoadingIndicatorView aviPt;

    public int getContentView() {
        return R.layout.pin_tuan_fragment;
    }

    private void initData() {
        zhongChouRecycle.setLayoutManager(new LinearLayoutManager(getContext()));
        selectCheck(0);
    }

    //点击已拼数
    private void clickYiPin() {
        CacheKit.PinTuan.YP_SHU_LIANG = !CacheKit.PinTuan.YP_SHU_LIANG;
        CacheKit.PinTuan.ZUI_XIN = false;
        CacheKit.PinTuan.C_TUAN_SHU = true;
        JSONObject orderBy = new JSONObject();
        if (CacheKit.PinTuan.YP_SHU_LIANG) {
            orderBy.put("buy_count", "asc");
            ToolsKit.setRadioDrawableRight(ptuanRadYiPin, R.mipmap.jiageshang);

        } else {
            orderBy.put("buy_count", "desc");
        }
        CacheKit.PinTuan.NOW_ORDER_BY = orderBy;
        CacheKit.PinTuan.NOW_PAGE_NUMBER = 1;
        getFirstPtData(CacheKit.PinTuan.NOW_PAGE_NUMBER, CacheKit.PinTuan.NOW_PAGE_SIZE, CacheKit.PinTuan.NOW_ORDER_BY);
    }

    //点击成团数
    private void clickChengTuan() {

        CacheKit.PinTuan.C_TUAN_SHU = !CacheKit.PinTuan.C_TUAN_SHU;
        CacheKit.PinTuan.ZUI_XIN = false;
        CacheKit.PinTuan.YP_SHU_LIANG = true;
        JSONObject orderBy = new JSONObject();
        if (CacheKit.PinTuan.C_TUAN_SHU) {
            orderBy.put("group_count", "asc");
            ToolsKit.setRadioDrawableRight(ptuanRadChengTuan, R.mipmap.jiageshang);

        } else {
            orderBy.put("group_count", "desc");
        }
        CacheKit.PinTuan.NOW_ORDER_BY = orderBy;
        CacheKit.PinTuan.NOW_PAGE_NUMBER = 1;
        getFirstPtData(CacheKit.PinTuan.NOW_PAGE_NUMBER, CacheKit.PinTuan.NOW_PAGE_SIZE, CacheKit.PinTuan.NOW_ORDER_BY);
    }

    // 点击最新
    private void clickZuiXin() {
        CacheKit.PinTuan.ZUI_XIN = !CacheKit.PinTuan.ZUI_XIN;
        CacheKit.PinTuan.C_TUAN_SHU = true;
        CacheKit.PinTuan.YP_SHU_LIANG = true;
        JSONObject orderBy = new JSONObject();
        if (CacheKit.PinTuan.ZUI_XIN) {
            orderBy.put("create_time", "asc");
            ToolsKit.setRadioDrawableRight(ptuanRadZuiXin, R.mipmap.jiageshang);
        } else {
            orderBy.put("create_time", "desc");
        }
        CacheKit.PinTuan.NOW_ORDER_BY = orderBy;
        CacheKit.PinTuan.NOW_PAGE_NUMBER = 1;
        getFirstPtData(CacheKit.PinTuan.NOW_PAGE_NUMBER, CacheKit.PinTuan.NOW_PAGE_SIZE, CacheKit.PinTuan.NOW_ORDER_BY);
    }

    //    查询第一页数据
    private void getFirstPtData(int nowPageNumber, int nowPageSize, JSONObject nowOrderBy) {
        CacheKit.YouXuan.NOW_PAGE_NUMBER = 1;
        CacheKit.YouXuan.NOW_PAGE_LAST = false;
        JSONObject para = new JSONObject();
        para.put("pageNumber", nowPageNumber);
        para.put("pageSize", nowPageSize);
        para.put("orderBy", nowOrderBy);
        para.put("activityId", activityId);
        LogKit.E("aaaa ---->   ", "  " + para);
        startLoading();
        new Handler().postDelayed(() -> {
            stopLoading();
            initAdapter();
        }, 1000);

//        startLoading();
//        new HttpUtils().sendPOST(
//                (response, code) ->
//                {
//                    stopLoading();
//                    LogKit.E("  获取第一页数据  ---> ", response);
//                    PtResponse ptResponse = JSONObject.parseObject(response, PtResponse.class);
//                    CacheKit.YouXuan.NOW_PAGE_NUMBER = ptResponse.getPageNumber();
//                    LogKit.E("aaaa ---->   ", "  " + ptResponse.isLastPage());
//                    CacheKit.YouXuan.NOW_PAGE_LAST = ptResponse.isLastPage();
//                    List<MultiItemEntity> list = new ArrayList<>();
//                    for (MultiItemEntity e : ptResponse.getList()) {
//                        list.add(e);
//                    }
//                    ptAdapter.setNewData(list);
//                    ptAdapter.loadMoreComplete();
//                    net_scro.setFocusableInTouchMode(true);
//                    net_scro.scrollTo(0, srcToHeight());
//                },
//                (call, e, id) ->
//                {
//                    LogKit.E("  爆款信息---> ", e.getMessage());
//                })
//                .sendAll(CONST.HTTP + CONST.OPTION_PT, para);

    }

    private void initAdapter() {
        ArrayList<PinTEntity> arrayList = new ArrayList<>();
        arrayList.add(new PinTEntity());
        arrayList.add(new PinTEntity());
        arrayList.add(new PinTEntity());
        arrayList.add(new PinTEntity());
        pinTAdapter = new PinTAdapter(0, arrayList);
        zhongChouRecycle.setAdapter(pinTAdapter);
        pinTAdapter.setOnItemClickListener((adapter, view, position) -> {
            ToolsKit.go(PinTuanInfoActivity.class);
        });
    }

    //下拉加载数据
    private void loadData() {
        JSONObject para = new JSONObject();
        LogKit.E("aaaa ---->   ", "  " + CacheKit.YouXuan.NOW_PAGE_LAST);
        if (CacheKit.YouXuan.NOW_PAGE_LAST) {
            ToastUtils.showShort("已经最后一页");
            refreshLayout.setEnableLoadMore(false);
            refreshLayout.finishLoadMore();
        } else {
            para.put("pageNumber", (CacheKit.PinTuan.NOW_PAGE_NUMBER += 1));
            para.put("pageSize", CacheKit.PinTuan.NOW_PAGE_SIZE);
            para.put("orderBy", CacheKit.PinTuan.NOW_ORDER_BY);
            para.put("activityId", activityId);
            aviPt.setVisibility(View.VISIBLE);
            refreshLayout.setEnableLoadMore(false);

            new OkHttpKit().send(
                    response200 -> {
                        stopLoading();
                    },
                    error401 -> {
                        LogKit.E("success401 ---->   ", "  " + error401);
                    },
                    error -> {
                        LogKit.E("error ---->   ", "  " + error);
                    }
            ).post(CONST.OPTION_PT, para, getActivity());

        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(getContentView(), container, false);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    //清空所有样式
    public void clearClick() {
        ptuanRadZuiXin.setChecked(false);
        ptuanRadChengTuan.setChecked(false);
        ptuanRadYiPin.setChecked(false);
        ToolsKit.setRadioDrawableRight(ptuanRadZuiXin, R.mipmap.jiagemoren);
        ToolsKit.setRadioDrawableRight(ptuanRadChengTuan, R.mipmap.jiagemoren);
        ToolsKit.setRadioDrawableRight(ptuanRadYiPin, R.mipmap.jiagemoren);

    }

    //选中按钮
    public void selectCheck(int postion) {
        stopLoading();
        clearClick();
        switch (postion) {
            case 0:
                ptuanRadZuiXin.setChecked(true);
                clickZuiXin();
                break;
            case 1:
                ptuanRadChengTuan.setChecked(true);
                clickChengTuan();
                break;
            case 2:
                ptuanRadYiPin.setChecked(true);
                clickYiPin();
                break;
            default:
                break;
        }

    }

    @OnClick({R.id.ptuan_rad_zui_xin, R.id.ptuan_rad_cheng_tuan, R.id.ptuan_rad_yi_pin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ptuan_rad_zui_xin:
                ToolsKit.setSleep1000(ptuanRadZuiXin);
                selectCheck(0);
                break;
            case R.id.ptuan_rad_cheng_tuan:
                ToolsKit.setSleep1000(ptuanRadChengTuan);
                selectCheck(1);
                break;
            case R.id.ptuan_rad_yi_pin:
                ToolsKit.setSleep1000(ptuanRadYiPin);
                selectCheck(2);
                break;
        }
    }

    private void startLoading() {
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setVisibility(View.GONE);
        aviPt.setVisibility(View.VISIBLE);
    }

    private void stopLoading() {
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
        refreshLayout.setEnableLoadMore(true);
        aviPt.setVisibility(View.GONE);
        refreshLayout.setVisibility(View.VISIBLE);
//        new Handler().postDelayed(() -> {

//        }, 300);
    }

}
